//
//  VCAutoReply.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/16.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VCAutoReply: VCBase {
    
    // 内容框
    private lazy var uitableView : UITableView = {
        let uiH = SCREEN_HEIGHT - realHeight - MARGIN50
        let ui = UITableView(frame: CGRect(x: 0, y: realHeight, width: SCREEN_WIDTH, height: uiH), style: .plain)
        return ui
    }()
    
    // 输入框
    private lazy var chatInput: UIView = {
        let ui = UIView(frame: CGRect(x: 00, y: realHeight + uitableView.bounds.height, width: SCREEN_WIDTH, height: MARGIN50))
        ui.backgroundColor = UIColor.init(patternImage: UIImage(named: "chat_bottom_bg")!)
        return ui
    }()
    
    // 输入图片
    private lazy var inputText: UITextField = {
        let ui = UITextField(frame: CGRect(x: MARGIN10, y: 7, width: SCREEN_WIDTH - 98, height: 30))
        ui.font = UIFont.systemFont(ofSize: 13)
        ui.background = UIImage(named: "chat_bottom_textfield")
        return ui
    }()
    
    // 笑脸图片
    private lazy var smileImg: UIButton = {
        let ui = UIButton(iconName: "chat_bottom_smile")
        ui.frame = CGRect(x: inputText.frame.maxX, y: 0, width: 44, height: 44)
        return ui
    }()
    
    // 加号图片
    private lazy var cirleAddImg: UIButton = {
        let ui = UIButton(iconName: "chat_bottom_add")
        ui.frame = CGRect(x: smileImg.frame.maxX, y: 0, width: 44, height: 44)
        return ui
    }()
    
    // 聊天内容文本
    private lazy var chatFrames = ChatFrame().getChatFrame()
    
    // 表情布局
    private lazy var emoticonview = CustomKeyboardView { (emotion) in
        self.inputText.showTextEmoji(emoticon: emotion)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_set()
        init_views()
        init_event()
    }
    
    @objc func dismissVc() -> Void {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func changeKeyBoard(notification:Notification) -> Void {
        guard let userInfo = notification.userInfo else {
            return
        }
        guard let keyboardHeight = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else {
            return
        }
        let offsetY = keyboardHeight.origin.y - view.frame.size.height
        UIView.animate(withDuration: duration) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
        }
        // 滑动到顶部
        scrollerToTop()
    }
    
    private func scrollerToTop() -> Void {
        guard let frames = chatFrames else {
            return
        }
        let indexPath = NSIndexPath.init(row: frames.count - 1, section: 0)
        uitableView.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: 滑动数据
extension VCAutoReply: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return chatFrames?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.cellForRow(at: indexPath) as? TableViewCellChat
        if cell == nil {
            cell = TableViewCellChat(style: .default, reuseIdentifier: "tableview_cell_chat_id")
        }
        cell!.chatFrame = chatFrames![indexPath.row]
        return cell!
    }
}

// MARK: 滑动代理
extension VCAutoReply: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let frames = chatFrames else {
            return 0
        }
        let chatFrame = frames[indexPath.row]
        return chatFrame.rowHeigth ?? 0
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

// MARK: 初始化
extension VCAutoReply {
    
    @objc func clickAddImg() -> Void {
        // 校验权限
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            self.show(text: "您没有权限访问相册")
            return
        }
        // 显示相册控制器
        let vc = UIImagePickerController()
        // 设置代理
        vc.delegate = self
        // 允许编辑图片
        vc.isEditing = true
        present(vc, animated: true, completion: nil)
    }
    
    @objc func clickSmilePic() -> Void {
        UIView.animate(withDuration: 0.4, animations: {
            // 退出键盘
            self.inputText.resignFirstResponder()
            // 设置键盘
            self.inputText.inputView = self.inputText.inputView == nil ? self.emoticonview : nil
        }) { (isOK) in
            // 激活键盘
            if isOK {
                self.inputText.becomeFirstResponder()
            }
        }
    }
    
    private func init_event() -> Void {
        smileImg.addTarget(self, action: #selector(clickSmilePic), for: .touchUpInside)
        cirleAddImg.addTarget(self, action: #selector(clickAddImg), for: .touchUpInside)
    }
    
    func init_set() -> Void {
        // 左箭头按钮
        let backItem = UIBarButtonItem(image: UIImage(named: "arrow_back"), style: .done, target: self, action: #selector(dismissVc))
        navigationItem.leftBarButtonItem = backItem
        // 去除分割线
        uitableView.separatorStyle = .none
        // cell不可点击
        uitableView.allowsSelection = false
        // textfield适配光标
        let leftMarginView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 1))
        inputText.leftView = leftMarginView
        inputText.leftViewMode = .always
        inputText.returnKeyType = .send
        // 聊天背景颜色
        uitableView.backgroundColor = COLOR_BACKGROUND
        // 注册代理
        inputText.delegate = self
        uitableView.delegate = self
        uitableView.dataSource = self
        // 弹出键盘
        NotificationCenter.default.addObserver(self, selector: #selector(changeKeyBoard(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }
    
    private func init_views() -> Void {
        // 添加到子View
        chatInput.addSubview(smileImg)
        chatInput.addSubview(inputText)
        chatInput.addSubview(cirleAddImg)
        // 添加到父View
        view.addSubview(chatInput)
        view.addSubview(uitableView)
        // 滑动到顶部
        scrollerToTop()
    }
}

// MARK: 不变
extension VCAutoReply: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        guard let text = textField.text else {
            return true
        }
        // 我方发送
        sendMsg(msg: text, type: "0",img: nil)
        // 对方发送
        sendMsg(msg: "很抱歉，不能理解您的意思!", type: "1",img: nil)
        // 输入框置空
        inputText.text = ""
        return true
    }
    
    private func sendMsg(msg:String,type:String,img:UIImage?) {
        let bean = ChatBean()
        // 类型
        bean.type = type
        // 正文
        bean.text = msg
        // 图片
        if img != nil {
            bean.picture = img
        }
        // 当前时间
        let formatter = DateFormatter()
        formatter.dateFormat = "今天 HH:mm"
        bean.time = formatter.string(from: Date())
        // 是否显示时间
        guard let frames = chatFrames else {
            return
        }
        let lastFrame = frames.last
        if let hidden = lastFrame?.chatBean?.time?.elementsEqual(bean.time ?? "") {
            bean.isHidden = hidden
        }
        // 添加数据
        let chat = ChatFrame()
        chat.chatBean = bean
        chatFrames?.append(chat)
        // 刷新数据
        uitableView.reloadData()
        // 滑动到顶部
        scrollerToTop()
    }
}

// MARK: 相册代理
extension VCAutoReply: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        var img = info[.originalImage] as! UIImage
        if picker.isEditing {
            img = info[.editedImage] as! UIImage
        }
        let scaleImg = img.scaleToWidth(width: 700)
        // 发送
        sendMsg(msg: "", type: "0", img: scaleImg)
        // 回复
        sendMsg(msg: "很抱歉，不能理解您的意思!", type: "1",img: nil)
        
        dismiss(animated: true, completion: nil)
    }
}
